﻿using Commons;
using COSSnippet;
using Hei.Captcha;
using IRMSService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PayPal.Api;
using Redis;
using RMSModel;
using RMSModel.Common;
using RMSModel.VMModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebApplication2.Models;

namespace RMS.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class SysController : ControllerBase
    {
        public PaypalService service1 = new PaypalService();
        public ILoginService service;
        private readonly SecurityCodeHelper _securityCode;
        private readonly IRedisService redisService;
        
        public SysController( ILoginService service, SecurityCodeHelper _securityCode, IRedisService redisService)
        {
            this.service = service;
            this._securityCode = _securityCode;
            this.redisService = redisService;
        }


        [HttpPost]
        public ResultType<string> login([FromBody] VMUser data)
        {
            return service.login(data.LoginName,data.Password,data.guid,data.code);
        }
        [HttpPost]
        public ResultType<Dictionary<string ,object>> UpdateFile()
        {
            ResultType<Dictionary<string, object>> result = new ResultType<Dictionary<string, object>>();
            PictureOperationModel pic = new PictureOperationModel();
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                     Request.Form.Files[0].CopyTo(memoryStream);

                    if (memoryStream.Length < 20971520)
                    {
                        var file = new AppFile()
                        {
                            Content = memoryStream.ToArray(),
                            Id =Guid.NewGuid().ToString()
                        };
                        string key = file.Id + ".png";
                        pic.UploadWithPicOperation(key,file.Content);
                        result.Data.Add("url", string.Format("https://bosswang-1255687113.cos.ap-shanghai.myqcloud.com/{0}", key)) ;
                        result.Data.Add("file", File(file.Content, "image/png").FileContents);
                    }
                    else
                    {
                        result.ResultCode = 1;
                        result.ResultMsg = "文件大小超过20M！";
                        return result;
                    }
                    
                }

            }
            catch (Exception ex)
            {
                result.ResultCode = 1;
                result.ResultMsg = ex.Message;
            }
            return result;
        }
        [HttpGet]
        public ResultType<Dictionary<string,object>> GetVerifyCode()
        {
            ResultType <Dictionary<string, object>> result =new  ResultType<Dictionary<string, object>>();
            string guid = Guid.NewGuid().ToString();
            var code = _securityCode.GetRandomEnDigitalText(4).ToLower();
            var imgbyte = _securityCode.GetEnDigitalCodeByte(code);
            redisService.AddOrUpdateByKeyAsync(guid,code,DateTime.Now.AddSeconds(60));
            result.Data.Add("image", File(imgbyte, "image/png").FileContents);
            result.Data.Add("guid",guid);
            result.Data.Add("code", code);
            return result;
        }
        #region 菜单
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<Dictionary<string, object>> GetAllMenuByUser(string userId)
        {
            return service.GetAllMenuByUser(userId);
        }
       // [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public List<TreeModel> GetAllMenuTree()
        {
            return service.GetAllMenuTree();
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<menu> GetMenuById(int id)
        {
            return service.GetMenuById(id);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<List<VMMenu>> GetAllMenu()
        {
            return service.GetAllMenu();
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType AddMenu([FromBody] menu m, string userId)
        {
            m.createuser = userId;
            m.createtime = DateTime.Now;
            return service.AddMenu(m);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType UpdateMenu([FromBody] menu data, string userId)
        {
            data.updateuser= userId;
            data.updatetime = DateTime.Now;
            return service.UpdateMenu(data);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType DeleteMenu([FromBody] List<menu>  m)
        {
            return service.DeleteMenu(m);
        }
        #endregion

        #region 用户
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<List<VMUser>> GetAllUser()
        {
            return service.GetAllUser();
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<VMUser> GetUserByUserId(int id)
        {
            return service.GetUserByUserId(id);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType AddUser([FromBody] user m, string userId)
        {
            m.createtime = DateTime.Now;
            m.createuser = userId;
            return service.AddUser(m);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType UpdateUser([FromBody] user data, string userId)
        {
            data.updateuser = userId;
            data.updatetime = DateTime.Now;
            return service.UpdateUser(data);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType ResetUserPassword(int  id)
        {
            return service.ResetUserPassword(id);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType DeleteUser([FromBody] List< user> da)
        {
            return service.DeleteUser(da);
        }
        #endregion

        #region 角色
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<List<role>> GetAllRole()
        {
            return service.GetAllRole();
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType AddRole([FromBody] VMRole data, string userId)
        {
            data.createuser = userId;
            data.createtime = DateTime.Now;
            return service.AddRole(data);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType UpdateRole([FromBody] VMRole data, string userId)
        {
            data.updateuser = userId;
            data.updatetime = DateTime.Now;
            return service.UpdateRole(data);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<List<TreeListModel>> GetAllMenuRole()
        {
            return service.GetAllMenuRole();
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpGet]
        public ResultType<Dictionary<string, object>> GetRoleByRoleId(int id)
        {
            return service.GetRoleByRoleId(id);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public ResultType DeleteRole([FromBody] List< role> data)
        {
            return service.DeleteRole(data);
        }
        [ServiceFilter(typeof(TokenFilter))]
        [HttpPost]
        public void Logout(string userId)
        {
             service.Logout(userId);
        }
        #endregion

        public static readonly String PAYPAL_SUCCESS_URL = "http://121.4.95.243/api/Sys/success";
        public static readonly String PAYPAL_CANCEL_URL = "http://121.4.95.243/api/Sys/cancel";


        [HttpPost]
        public string pay()
        {
            //String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;http://121.4.95.243/
            //String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL; http://121.4.95.243/api/sys/cancel
            Payment payment = service1.createPayment(
                   500.00,
                   "USD",
                   PaypalPaymentMethod.paypal,
                   PaypalPaymentIntent.sale,
                   "payment description",
                   PAYPAL_CANCEL_URL,
                   PAYPAL_SUCCESS_URL);
            foreach (Links links in payment.links)
            {
                if (links.rel.Equals("approval_url"))
                {
                    return  links.href;
                }
            }
            return "redirect:/";
        }
        [HttpGet]
        public String cancel()
        {
            return "cancel";
        }
        [HttpGet]
        public String success(String paymentId, String payerId)
        {
            Payment payment = service1.executePayment(paymentId, payerId);
            if (payment.state.Equals("approved"))
            {
                return "success";
            }
            return "redirect:/";
        }
    }
}
